package com.saturday.web.translates.processor;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.saturday.web.translates.annotaion.JsonTranslater;
import com.saturday.web.translates.service.TranslateService;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TranslateProcessor {

    public static void translate(List<JsonTranslater> translaterList, Object data, Map<String, TranslateService> translateServiceMap) {
        if (data instanceof List) {
            /*如果为返回列表场景则转换成list，逐个处理*/
            List list = (List) data;
            for (Object object : list) {
                translate(translaterList, object, translateServiceMap);
            }
        } else if (data instanceof Set) {
            /*如果为返回列表场景则转换成list，逐个处理*/
            Set list = (Set) data;
            for (Object object : list) {
                translate(translaterList, object, translateServiceMap);
            }
        } else if (data instanceof PageInfo) {
            PageInfo pate = (PageInfo) data;
            List list = pate.getList();
            translate(translaterList, list, translateServiceMap);
        } else if (data != null && !ClassUtil.isBasicType(data.getClass()) && !ClassUtil.isSimpleTypeOrArray(data.getClass())) {
            /*如果为普通对象返回场景，则逐个处理*/
            translateHandle(translaterList, data, translateServiceMap);
        }
    }

    private static void translateHandle(List<JsonTranslater> translaterList, Object data, Map<String, TranslateService> translateServiceMap) {
        for (JsonTranslater jsonTranslater : translaterList) {
            TranslateService translateService = translateServiceMap.get(jsonTranslater.transName());
            List<Object> params = new ArrayList<>();
            String[] paramKeys = jsonTranslater.params();
            for (int i = 0; i < paramKeys.length; i++) {
                Field fieldKey = ReflectUtil.getField(data.getClass(), paramKeys[i]);
                params.add(ReflectUtil.getFieldValue(data, fieldKey));

            }
            Object result = translateService.execute(params.toArray());

            if (ObjectUtil.isNotNull(result)) {
                Map<String, Object> resultMap = JSONObject.parseObject(JSONObject.toJSONString(result));
                String[] toKeys = jsonTranslater.toKeys();
                String[] valueKeys = jsonTranslater.valueKeys();
                for (int i = 0; i < toKeys.length; i++) {
                    Field fieldValue = ReflectUtil.getField(data.getClass(), toKeys[i]);
                    if (null == fieldValue) {
                        continue;
                    }
                    ReflectUtil.setFieldValue(data, fieldValue, resultMap.get(valueKeys[i]));
                }
            }
        }
    }
}
